package com.ctakit.sdk.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

/**
 * Created by lizhenmin on 15/3/2.
 */
public class FileUtils {

	private static final String FOLDER_SEPARATOR = "/";

	private static final String EXTENSION_SEPARATOR = ".";

	/**
	 * 手机的缓存根目录
	 */
	private static String mDataRootPath = Environment.getExternalStorageDirectory().getAbsolutePath();;
	/**
	 * 保存Image的目录名
	 */
	private final static String FOLDER_NAME = "disk_cache";




	public static  File getCacheDir(Context context) {
		File cacheFifle = null;
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
			cacheFifle = getExternalCacheDir(context,FOLDER_NAME);
		}
		if(cacheFifle==null){
			File cacheDir = context.getCacheDir();
			if (cacheDir != null) {
				 cacheFifle = new File(cacheDir, FOLDER_NAME);
				if (!cacheFifle.mkdirs() && (!cacheFifle.exists() || !cacheFifle.isDirectory())) {

					return null;
				}
			}
		}
		return cacheFifle;
	}
	/**
	 * 获取储存Image的目录
	 * @return
	 */
	private static  String getStorageDirectory() {
		return mDataRootPath + FOLDER_SEPARATOR+FOLDER_NAME;
	}

	/**
	 * 保存Image的方法，有sd卡存储到sd卡，没有就存储到手机目录
	 * @param fileName
	 * @param bitmap
	 * @throws IOException
	 */
	public static  String savaBitmap(Context context, String fileName, Bitmap bitmap) throws IOException {
		if (bitmap == null) {
			return null;
		}
		File cacheDir = getCacheDir(context);
		if(cacheDir!=null){

			File file = new File(cacheDir.getAbsolutePath() + File.separator + fileName);
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
			return file.getPath();
		}else{
			return null;
		}

	}
	public static File savaBitmapToFile(Context context,Bitmap bitmap) throws IOException {
		if (bitmap == null) {
			return null;
		}
		File cacheFile = getImageCacheFile(context);
		if(cacheFile!=null){
			cacheFile.createNewFile();
			FileOutputStream fos = new FileOutputStream(cacheFile);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
			return cacheFile;
		}else{
			return null;
		}

	}


	/**
	 * 拷贝文件 
	 * @param oldPath
	 * @param newPath
	 * @return
	 */
	public static boolean copyFile(String oldPath, String newPath) {
		boolean isok = true;
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { //文件存在时
				InputStream inStream = new FileInputStream(oldPath); //读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1024];
				int length;
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; //字节数 文件大小
					//System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				fs.flush();
				fs.close();
				inStream.close();
			} else {
				isok = false;
			}
		} catch (Exception e) {
			// System.out.println("复制单个文件操作出错");
			// e.printStackTrace();
			isok = false;
		}
		return isok;

	}

	/**
	 * 删除SD卡或者手机的缓存图片和目录
	 */
	private static void deleteFile() {
		File dirFile = new File(getStorageDirectory());
		if (!dirFile.exists()) {
			return;
		}
		if (dirFile.isDirectory()) {
			String[] children = dirFile.list();
			for (int i = 0; i < children.length; i++) {
				new File(dirFile, children[i]).delete();
			}
		}

		dirFile.delete();
	}

	/**
	 * 检查是否存在SDCard
	 * 
	 * @return
	 */
	public static boolean hasSdcard() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isImage(String fileName) {

		if (!fileName.startsWith(".") && (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png"))) {
			File file = new File(fileName);
			if (!file.exists()) {
				return false;
			}
			return true;
		} else {
			return false;
		}
	}

	public static String getFileNameWithExtension(String path) {
		//int lastIndex = path.lastIndexOf(".");
		int firstIndex = path.lastIndexOf(FOLDER_SEPARATOR);
		return path.substring(firstIndex+1);
	}

	public static String getFileNameExtension(String path) {
		return getFileNameExtension(path, null);
	}

	public static String getFileNameExtension(String path, String defultValue) {
		if (path == null) {
			return defultValue;
		}
		int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
		if (extIndex == -1) {
			return defultValue;
		}
		int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
		if (folderIndex > extIndex) {
			return defultValue;
		}
		return path.substring(extIndex + 1);
	}

	public static String getFileSize(File file){
		String size = "";
		if(file.exists() && file.isFile()){
			long fileS = file.length();
			DecimalFormat df = new DecimalFormat("#.00");
			if (fileS < 1024) {
				size = df.format((double) fileS) + "BT";
			} else if (fileS < 1048576) {
				size = df.format((double) fileS / 1024) + "KB";
			} else if (fileS < 1073741824) {
				size = df.format((double) fileS / 1048576) + "MB";
			} else {
				size = df.format((double) fileS / 1073741824) +"GB";
			}
		}else if(file.exists() && file.isDirectory()){
			size = "";
		}else{
			size = "0BT";
		}
		return size;
	}


	private static  File getExternalCacheDir(Context context, String cacheName) {
		File cacheDir = context.getExternalCacheDir();
		if (cacheDir != null) {
			File result = new File(cacheDir, cacheName);
			if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) {

				return null;
			}
			return result;
		}

		return null;
	}

	public static File getImageCacheFile(Context context) {
		if (getCacheDir(context) != null) {
			return new File(getCacheDir(context).getAbsolutePath() + "/" + System.currentTimeMillis() + (int) (Math.random() * 1000) + ".jpg");
		}
		return null;
	}


}